<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>分类参数</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图区域 -->
    <el-card>
      <!-- 警告区域 -->
      <el-alert show-icon title="注意：只允许为第三级分类设置相关参数！" type="warning" :closable="false"></el-alert>

      <!-- 选择商品分类区域 -->
      <el-row class="cat_opt">
        <el-col>
          <span>选择商品分类：</span>
          <!-- 选择商品分类的级联选择框 -->
          <el-cascader
            expand-trigger="hover"
            :options="cateOptions"
            :props="catelist"
            v-model="selectedCateKeys"
            @change="cateQueryChange"
            clearable
            filterable
            class="queryCascader"
          ></el-cascader>
        </el-col>
      </el-row>

      <!-- 标签页 -->
      <el-tabs v-model="activeName" @tab-click="tabsClick">
        <el-tab-pane label="动态参数" name="many">
          <!-- 添加参数按钮 -->
          <el-button type="primary" :disabled="isOpen" @click="addDialogVisible = true">添加参数</el-button>
          <el-table :data="tableList_Many" border style="width: 100%">
            <!-- 展开行 -->
            <el-table-column type="expand" width="50">
              <template slot-scope="scoped">
                <el-tag
                  v-for="(item,i) in scoped.row.attr_vals"
                  :key="i"
                  closable
                  @close="tagDelete(scoped.row,i)"
                >{{item}}</el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="scoped.row.inputVisible"
                  v-model="scoped.row.inputValue"
                  ref="saveTagInput"
                  size="mini"
                  @keyup.enter.native="handleInputConfirm(scoped.row)"
                  @blur="handleInputConfirm(scoped.row)"
                ></el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scoped.row)"
                >+ 新增</el-button>
              </template>
            </el-table-column>
            <!-- 索引列 -->
            <el-table-column align="center" type="index" label="序号" width="180"></el-table-column>
            <el-table-column align="center" prop="attr_name" label="分类名称" width="180"></el-table-column>
            <el-table-column align="center" label="操作">
              <template v-slot="scope">
                <el-button
                  size="mini"
                  type="primary"
                  icon="el-icon-edit"
                  @click="showEditDialog(scope.row.attr_id)"
                >编辑</el-button>
                <el-button
                  size="mini"
                  type="danger"
                  icon="el-icon-delete"
                  @click="removeParams(scope.row.attr_id)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>

        <el-tab-pane label="静态属性" name="only">
          <!-- 添加属性按钮 -->
          <el-button type="primary" :disabled="isOpen" @click="addDialogVisible = true">添加属性</el-button>
          <el-table :data="tableList_Only" border style="width: 100%">
            <!-- 展开行 -->
            <el-table-column type="expand" width="50">
              <template v-slot="scoped">
                <el-tag
                  v-for="(item,i) in scoped.row.attr_vals"
                  :key="i"
                  closable
                  @close="tagDelete(scoped.row,i)"
                >{{item}}</el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="scoped.row.inputVisible"
                  v-model="scoped.row.inputValue"
                  ref="saveTagInput"
                  size="mini"
                  @keyup.enter.native="handleInputConfirm(scoped.row)"
                  @blur="handleInputConfirm(scoped.row)"
                ></el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scoped.row)"
                >+ 新增</el-button>
              </template>
            </el-table-column>

            <!-- 索引列 -->
            <el-table-column align="center" type="index" label="序号" width="180"></el-table-column>
            <el-table-column align="center" prop="attr_name" label="属性名称" width="180"></el-table-column>
            <el-table-column align="center" label="操作">
              <template v-slot="scope">
                <el-button
                  size="mini"
                  type="primary"
                  icon="el-icon-edit"
                  @click="showEditDialog(scope.row.attr_id)"
                >编辑</el-button>
                <el-button
                  size="mini"
                  type="danger"
                  icon="el-icon-delete"
                  @click="removeParams(scope.row.attr_id)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>

      <!-- 添加参数的对话框 -->
      <el-dialog
        :title="'添加' + titleText"
        :visible.sync="addDialogVisible"
        width="50%"
        @close="addDialogClosed"
      >
        <!-- 添加参数的对话框 -->
        <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="100px">
          <el-form-item :label="titleText" prop="attr_name">
            <el-input v-model="addForm.attr_name"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="addDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addParamsSubmit">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
export default {
  data: function() {
    return {
      catelist: {
        label: "cat_name",
        value: "cat_id",
        children: "children"
      },
      //下拉的列表数据
      cateOptions: [],
      //   下拉选中的值的位置
      selectedCateKeys: [],
      activeName: "many",
      //   table中的数据
      tableList_Many: [],
      tableList_Only: [],
      addForm: {
        attr_name: ""
      },
      addDialogVisible: false,
      addFormRules: {
        attr_name: [{ required: true, message: "请输入内容", trigger: "blur" }]
      }
    };
  },
  created: function() {
    this.getParamsList();
  },
  methods: {
    getParamsList: async function() {
      const { data: res } = await this.$http.get("/categories", {
        params: {
          type: 3
        }
      });
      if (res.meta.status !== 200) {
        this.$message.error("获取商品分类下拉列表数据失败!");
        return;
      }
      this.cateOptions = res.data;
    },
    //根据所选的分类id和当前所处在的面板table,获取对应的参数
    getData: async function() {
      const { data: res } = await this.$http.get(
        `categories/${this.catId}/attributes`,
        {
          params: { sel: this.activeName }
        }
      );
      if (res.meta.status !== 200) {
        return this.$message.error("获取面板数据失败");
      }
      res.data.forEach(item => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(" ") : [];
        // 控制文本框的显示与隐藏
        item.inputVisible = false;
        // 文本框中输入的值
        item.inputValue = "";
      });
      if (this.activeName === "many") {
        this.tableList_Many = res.data;
      } else {
        this.tableList_Only = res.data;
      }
    },
    cateQueryChange: function() {
      const len = this.selectedCateKeys.length;
      if (len !== 3) {
        this.$message.warning("需要选择第三级的分类哦!");
        this.selectedCateKeys = [];
        return;
      }
      this.getData();
    },
    tabsClick: function() {
      if (this.selectedCateKeys.length !== 3) {
        return this.$message.warning("您还未选择上方的分类数据(3级)");
      }
      this.getData();
    },
    showEditDialog: function() {},
    removeParams: function(_id) {
      this.$confirm("此操作将永久删除该数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        lockScroll: false
      })
        .then(async () => {
          const { data: res } = await this.$http.delete(
            `/categories/${this.catId}/attributes/${_id}`
          );
          if (res.meta.status !== 200) {
            this.$message({
              showClose: true,
              message: "删除失败",
              type: "error"
            });
            return;
          }
          this.$message({
            showClose: true,
            message: "删除成功",
            type: "success"
          });
          this.getData();
        })
        .catch(() => {});
    },
    addDialogClosed: function() {
      this.addForm.attr_name = "";
      this.$refs.addFormRef.resetFields();
    },
    addParamsSubmit: function() {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) {
          this.$message.warning("请检查输入的信息是否有误!");
          return;
        }
        const { data: res } = await this.$http.post(
          `/categories/${this.catId}/attributes`,
          {
            attr_name: this.addForm.attr_name,
            attr_sel: this.activeName
          }
        );

        if (res.meta.status !== 201) {
          this.$message.error("添加参数失败了!");
          return;
        }
        this.$message.success("添加参数成功了!");
        this.addDialogVisible = false;
        this.getData();
      });
    },
    // 删除动态参数
    tagDelete: function(_row, _index) {
      this.$confirm("此操作将永久删除该数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        lockScroll: false
      })
        .then(async () => {
          _row.attr_vals.splice(_index, 1);
          this.putData(_row, "删除");
        })
        .catch(() => {});
    },
    // 文本框失去焦点,或者按下enter键
    handleInputConfirm: async function(_dataInfo) {
      if (_dataInfo.inputValue.trim().length === 0) {
        _dataInfo.inputValue = "";
        _dataInfo.inputVisible = false;
        return;
      }
      _dataInfo.attr_vals.push(_dataInfo.inputValue.trim());
      _dataInfo.inputValue = "";
      //调用发送请求的函数,添加到后台
      this.putData(_dataInfo, "添加");
      _dataInfo.inputVisible = false;
    },
    showInput: function(row) {
      row.inputVisible = true;
      //   自动获得焦点
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },
    // 改变或者删除参数公用的复用函数
    putData: async function(_dataInfo, _text) {
      const { data: res } = await this.$http.put(
        `categories/${_dataInfo.cat_id}/attributes/${_dataInfo.attr_id}`,
        {
          attr_name: _dataInfo.attr_name,
          attr_sel: this.activeName,
          attr_vals: _dataInfo.attr_vals.join(" ")
        }
      );
      if (res.meta.status !== 200) {
        this.$message.error(_text + "失败");
        return;
      }

      this.$message.success(_text + "成功!");
    }
  },
  //   计算属性
  computed: {
    //计算属性控制按钮的状态
    isOpen: function() {
      if (this.selectedCateKeys.length !== 3) {
        return true;
      } else {
        return false;
      }
    },
    //当前的3级分类的id值
    catId: function() {
      const arr = this.selectedCateKeys;
      if (arr.length !== 3) {
        return null;
      } else {
        return arr[arr.length - 1];
      }
    },
    titleText: function() {
      if (this.activeName == "many") {
        return "动态参数";
      } else {
        return "静态属性";
      }
    }
  },
  //   监听器
  watch: {
    // 如果没有选择的数据清空table数据列表的暂存数组
    selectedCateKeys: function(val) {
      if (val.length === 0) {
        this.tableList_Many = [];
        this.tableList_Only = [];
      }
    }
  }
};
</script>
<style lang='less' scoped>
.cat_opt {
  margin: 15px 0;
}
.queryCascader {
  width: 330px;
}
.el-tabs,
.el-table {
  margin-top: 20px;
}
.el-tag {
  margin-right: 10px;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
</style>